function s = extractPart(q, top, left, type)
    if nargin == 3
        type = 2;
    end
    
    if type == 1
        s = extractPart1(q, top, left);
    else
        s = extractPart2(q, top, left);
    end
end

function s = extractPart1(q, top, left)
    % q is 16x16 matrix, top, left is the position of DCT Coef
    q0=q(1:8,1:8);
    q1=q(1:8,9:16);
    q2=q(9:16,1:8);
    q3=q(9:16,9:16);
    bq0 = idct2(q0,8,8)+128;
    bq1 = idct2(q1,8,8)+128;
    bq2 = idct2(q2,8,8)+128;
    bq3 = idct2(q3,8,8)+128;
    bq = [bq0,bq1;bq2,bq3];
    sq = bq(top:top+7,left:left+7);
    s = dct2((sq-128), 8, 8);
end

function s = extractPart2(q, top, left)
    % q is 16x16 matrix, top, left is the position of DCT Coef
    q0=q(1:8,1:8);
    if (top==1)&&(left==1)
        s=q0;
        return;
    end
    q1=q(1:8,9:16);
    q2=q(9:16,1:8);
    q3=q(9:16,9:16);
    
    h0a=hxMAT(9-top);
    h0b=hxMAT(9-left)';
    h0=h0a*q0*h0b;
    
    h1a=h0a;
    h1b=hxMAT(left-1);
    h1=h1a*q1*h1b;
    
    h2a=hxMAT(top-1)';
    h2b=h0b;
    h2=h2a*q2*h2b;

    h3a = h2a;
    h3b = h1b;
    h3=h3a*q3*h3b;
    s = h0+h1+h2+h3;
end

function ret = hxMAT(dimension)
    z = zeros(8,8);
    z(1:dimension,9-dimension:8)=eye(dimension);
    ret = dct2(z, 8, 8);
end
